package com.gewu.pm.ui.fragment.clockin;

import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.gewu.pm.R;
import com.gewu.pm.aop.Permissions;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.TitleBarFragment;
import com.gewu.pm.ui.activity.CameraActivity;
import com.gewu.pm.ui.activity.clockin.ClockInManageActivity;
import com.gewu.pm.ui.activity.clockin.ClockInRecordActivity;
import com.gewu.pm.ui.activity.clockin.ClockInRulesActivity;
import com.gewu.pm.ui.dialog.MenuDialog;
import com.hjq.base.BaseDialog;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import timber.log.Timber;

/**
 * 打卡 Fragment
 */
public final class ClockInFragment extends TitleBarFragment<ClockInManageActivity>
        implements View.OnClickListener {

    private TextView mWeekDayView;
    private TextView mDateView;
    private TextView mAttendanceRulesView;

    private LinearLayout mSignInLayout;
    private ImageView mSignInBgView;
    private TextView mSignInStatusView;
    private TextView mSignInTimeView;
    private TextView mSignInActionView;
    private TextView mSignInAddressView;

    private LinearLayout mSignOutLayout;
    private ImageView mSignOutBgView;
    private TextView mSignOutStatusView;
    private TextView mSignOutTimeView;
    private TextView mSignOutActionView;
    private TextView mSignOutAddressView;

    private TextView tvAttendanceRecord;

    private boolean mIsSignedIn = false;
    private boolean mIsSignedOut = false;
    private String mSignInPhotoPath;
    private String mSignOutPhotoPath;

    public static ClockInFragment newInstance() {
        return new ClockInFragment();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.clock_in_fragment;
    }

    @Override
    protected void initView() {
        mWeekDayView = findViewById(R.id.tv_week_day);
        mDateView = findViewById(R.id.tv_date);
        mAttendanceRulesView = findViewById(R.id.tv_attendance_rules);

        mSignInLayout = findViewById(R.id.ll_sign_in);
        mSignInBgView = findViewById(R.id.iv_sign_in_bg);
        mSignInStatusView = findViewById(R.id.tv_sign_in_status);
        mSignInTimeView = findViewById(R.id.tv_sign_in_time);
        mSignInActionView = findViewById(R.id.tv_sign_in_action);
        mSignInAddressView = findViewById(R.id.tv_sign_in_address);

        mSignOutLayout = findViewById(R.id.ll_sign_out);
        mSignOutBgView = findViewById(R.id.iv_sign_out_bg);
        mSignOutStatusView = findViewById(R.id.tv_sign_out_status);
        mSignOutTimeView = findViewById(R.id.tv_sign_out_time);
        mSignOutActionView = findViewById(R.id.tv_sign_out_action);
        mSignOutAddressView = findViewById(R.id.tv_sign_out_address);

        tvAttendanceRecord = findViewById(R.id.tv_attendance_record);

        setOnClickListener(mSignInLayout, mSignOutLayout, tvAttendanceRecord, mAttendanceRulesView);
    }

    @Override
    protected void initData() {
        updateDateInfo();
    }

    /**
     * 更新日期信息
     */
    private void updateDateInfo() {
        Calendar calendar = Calendar.getInstance();
        
        // 设置星期
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        mWeekDayView.setText(weekDays[dayOfWeek - 1]);
        
        // 设置日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        mDateView.setText(dateFormat.format(calendar.getTime()));
    }

    /**
     * 获取当前时间
     */
    private String getCurrentTime() {
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
        return timeFormat.format(Calendar.getInstance().getTime());
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.ll_sign_in) {
            onSignInClick();
        } else if (viewId == R.id.ll_sign_out) {
            onSignOutClick();
        } else if (viewId == R.id.tv_attendance_record) {
            ClockInRecordActivity.start(getAttachActivity());
        } else if (viewId == R.id.tv_attendance_rules) {//打卡规则
            ClockInRulesActivity.start(getAttachActivity());
        }
    }

    /**
     * 签到点击
     */
    private void onSignInClick() {
        if (mIsSignedIn) {
            toast("已签到");
            return;
        }
        
        // 显示底部弹窗
        showPhotoDialog(true);
    }

    /**
     * 签退点击
     */
    private void onSignOutClick() {
        if (mIsSignedOut) {
            toast("已签退");
            return;
        }
        
        // 检查是否已签到
        if (!mIsSignedIn) {
            toast("还没签到成功");
            return;
        }
        
        // 显示底部弹窗
        showPhotoDialog(false);
    }

    /**
     * 显示拍照弹窗
     * @param isSignIn true=签到，false=签退
     */
    private void showPhotoDialog(boolean isSignIn) {
        new MenuDialog.Builder(getAttachActivity())
                .setList("拍照上传")
                .setCancel("取消")
                .setListener(new MenuDialog.OnListener<String>() {
                    @Override
                    public void onSelected(BaseDialog dialog, int position, String s) {
                        if (position == 0) {
                            // 拍照上传
                            if (isSignIn) {
                                takeSignInPhoto();
                            } else {
                                takeSignOutPhoto();
                            }
                        }
                    }
                })
                .show();
    }

    /**
     * 签到拍照
     */
    @Permissions({android.Manifest.permission.CAMERA})
    private void takeSignInPhoto() {
        CameraActivity.start(getAttachActivity(), new CameraActivity.OnCameraListener() {
            @Override
            public void onSelected(File file) {
                mSignInPhotoPath = file.getAbsolutePath();
                Timber.d("签到照片路径: %s", mSignInPhotoPath);
                toast("照片路径: " + mSignInPhotoPath);
                updateSignInStatus(true);
            }

            @Override
            public void onCancel() {
                Timber.d("取消签到拍照");
            }
        });
    }

    /**
     * 签退拍照
     */
    @Permissions({android.Manifest.permission.CAMERA})
    private void takeSignOutPhoto() {
        CameraActivity.start(getAttachActivity(), new CameraActivity.OnCameraListener() {
            @Override
            public void onSelected(File file) {
                mSignOutPhotoPath = file.getAbsolutePath();
                Timber.d("签退照片路径: %s", mSignOutPhotoPath);
                toast("照片路径: " + mSignOutPhotoPath);
                updateSignOutStatus(true);
            }

            @Override
            public void onCancel() {
                Timber.d("取消签退拍照");
            }
        });
    }

    /**
     * 更新签到状态
     */
    private void updateSignInStatus(boolean success) {
        if (success) {
            mIsSignedIn = true;
            mSignInBgView.setImageResource(R.drawable.shape_green_circle);
            mSignInStatusView.setText(R.string.sign_in_success);
            mSignInTimeView.setText(getCurrentTime());
            mSignInTimeView.setVisibility(View.VISIBLE);
            mSignInActionView.setVisibility(View.GONE);
            
            // 显示地址（模拟）
            mSignInAddressView.setText("某某某科技大厦");
            mSignInAddressView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 更新签退状态
     */
    private void updateSignOutStatus(boolean success) {
        if (success) {
            mIsSignedOut = true;
            mSignOutBgView.setImageResource(R.drawable.shape_green_circle);
            mSignOutStatusView.setText(R.string.sign_out_success);
            mSignOutTimeView.setText(getCurrentTime());
            mSignOutTimeView.setVisibility(View.VISIBLE);
            mSignOutActionView.setVisibility(View.GONE);
            
            // 显示地址（模拟）
            mSignOutAddressView.setText("某某某科技大厦");
            mSignOutAddressView.setVisibility(View.VISIBLE);
        }
    }
}
